package com.zzyl.nursing.service.impl;

import java.sql.Wrapper;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-17
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private ICheckInService checkinservice;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;



    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckInDetailVo selectCheckInById(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 查询老人信息
        checkInDetailVo.setCheckInElderVo(elderMapper.getElderByCheckInId(id));
        // 查询老人家属信息
        String remark = checkInMapper.getRemarkById(id);
        checkInDetailVo.setElderFamilyVoList(JSONUtil.toList(remark, ElderFamilyVo.class));
        // 查询入住配置信息
        checkInDetailVo.setCheckInConfigVo(checkInConfigMapper.selectCheckInConfigByCheckinId(id));
        // 查询合同信息
        checkInDetailVo.setContract(contractService.getOne(Wrappers.lambdaQuery(Contract.class).eq(Contract::getElderId, checkInDetailVo.getCheckInElderVo().getId())));
        return checkInDetailVo;
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCheckIn(CheckInApplyDto checkInApplyDto) {

        // 1. 检验老人是否已入住
        check(checkInApplyDto);


        // 2. 更新床位状态为已入住
        Bed bed = updateBedStatus(checkInApplyDto);


        // 3. 新增或更新老人信息
        Elder elder = insertOrUpdateElder(checkInApplyDto, bed);


        // 4. 新增签约办理
        insertContract(checkInApplyDto, elder);


        // 5. 新增入住信息
        CheckIn checkIn = insertCheckIn(checkInApplyDto, elder, bed);

        // 6. 新增入住配置信息
        boolean flag = insertCheckInConfig(checkInApplyDto, checkIn);
        return flag ? 1 : 0;
    }

    /**
     * 保存入住信息
     * @param checkInApplyDto
     * @param checkIn
     * @return
     */
    private boolean insertCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        // 6.1 设置入住表id
        checkInConfig.setCheckInId(checkIn.getId());
        // 6.2 保存入住配置信息
        boolean flag = checkInConfigService.save(checkInConfig);
        return flag;
    }

    /**
     * 新增入住信息
     *
     * @param checkInApplyDto
     * @param elder
     * @param bed
     * @return
     */
    @NotNull
    private CheckIn insertCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkIn);
        // 5.1 设置老人姓名
        checkIn.setElderName(elder.getName());
        // 5.2 设置老人id
        checkIn.setElderId(elder.getId());
        // 5.3 设置老人身份证号
        checkIn.setIdCardNo(elder.getIdCardNo());
        // 5.4 设置入住床位
        checkIn.setBedNumber(bed.getBedNumber());
        // 5.5设置家属信息
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        // 5.6 保存入住信息
        checkinservice.save(checkIn);
        return checkinservice.getOne(Wrappers.lambdaQuery(CheckIn.class).eq(CheckIn::getIdCardNo, checkIn.getIdCardNo()));
    }

    /**
     * 新增合同信息
     *
     * @param checkInApplyDto
     * @param elder
     */
    private void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        // 4.1 设置老人id
        contract.setElderId(elder.getId().intValue());
        // 4.2 设置合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        // 4.3 设置老人姓名
        contract.setElderName(elder.getName());
        // 4.4 设置开始时间
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        // 4.5 设置结束时间
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        // 4.6 保存签约信息
        contractService.save(contract);
    }

    /**
     * 检查老人是否已经入住
     *
     * @param checkInApplyDto
     */
    private void check(CheckInApplyDto checkInApplyDto) {
        LambdaQueryWrapper<Elder> wrapper = Wrappers.lambdaQuery(Elder.class)
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elder = elderService.getOne(wrapper);
        if (ObjectUtil.isNotNull(elder)) {
            // 1.1 老人已入住，进行提示
            throw new RuntimeException("老人已入住");
        }
    }

    /**
     * 新增或更新老人信息
     *
     * @param checkInApplyDto
     * @param bed
     * @return
     */
    @Nullable
    private Elder insertOrUpdateElder(CheckInApplyDto checkInApplyDto, Bed bed) {
        // 3.1 判断老人是否入住过
        LambdaQueryWrapper<Elder> wrapper = Wrappers.lambdaQuery(Elder.class)
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 0);
        Elder elder = elderService.getOne(wrapper);
        if (ObjectUtil.isNotNull(elder)) {
            // 3.2 老人入住过，更新老人信息
            BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
            elder.setBedNumber(bed.getBedNumber());
            elder.setStatus(1);
            elder.setBedId(bed.getId());
            elderService.updateById(elder);
            return elderService.getById(elder.getId());
        } else {
            // 3.3 老人未入住过，新增老人信息
            Elder elder2 = new Elder();
            BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder2);
            elder2.setBedNumber(bed.getBedNumber());
            elder2.setBedId(bed.getId());
            elderService.save(elder2);
            return elderService.getOne(Wrappers.lambdaQuery(Elder.class).eq(Elder::getIdCardNo, elder2.getIdCardNo()));
        }
    }

    /**
     * 更新床位状态信息
     *
     * @param checkInApplyDto
     * @return
     */
    private Bed updateBedStatus(CheckInApplyDto checkInApplyDto) {
        new LambdaUpdateChainWrapper<>(bedService.getBaseMapper())
                .eq(Bed::getId, checkInApplyDto.getCheckInConfigDto().getBedId())
                .set(Bed::getBedStatus, 1)
                .update();
        return bedService.getById(checkInApplyDto.getCheckInConfigDto().getBedId());
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }
}
